package com.cc.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cc.common.utils.PageUtils;
import com.cc.common.utils.R;
import com.cc.common.utils.ResponseData;
import com.cc.user.entity.CertificatePictureEntity;
import com.cc.user.entity.UserEntity;
import com.cc.user.feign.MallFeign;
import com.cc.user.service.CertificatePictureService;
import com.cc.user.service.EmployeeCustomerService;
import com.cc.user.service.UserService;
import com.cc.user.vo.CustomerDetailVo;
import com.cc.user.vo.OrderVo;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;


/**
 * 
 *
 * @author leifengyang
 * @email leifengyang@gmail.com
 * @date 2020-12-11 11:30:58
 */
@RestController
@RequestMapping("user/user")
@Api(tags="用户")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private EmployeeCustomerService employeeCustomerService;

    @Autowired
    private CertificatePictureService certificatePictureService;

    @Autowired
    private MallFeign orderFeignService;


    @PostMapping("/getUsersByMobilePermission")
    @ApiOperation("后台根据用户手机号、用户类型获取用户列表")
    public ResponseData<PageUtils> getUsersByMobilePermission(@RequestParam(required = true) Map<String,Object> params) {
        PageUtils page = userService.getUsersByMobilePermission(params);
        return ResponseData.success(page);
    }

    @PostMapping("/getUserDetailByUid")
    @ApiOperation("后台根据用户id获取用户详情")
    @ApiImplicitParam(name = "uid", value = "用户id", paramType = "query", dataType = "Long", required = true)
    public ResponseData<CustomerDetailVo> getUserDetailByUid(@RequestParam("uid")Long uid) {
        CustomerDetailVo customerDetailVo = employeeCustomerService.getCustomerDetailByCid(uid);

        List<CertificatePictureEntity> certificatePictureEntities = certificatePictureService.getPicturesByCid(uid);
        List<String> mentouPictures = new ArrayList<>();
        List<String> chengliePictures = new ArrayList<>();
        List<String> hetongPictures = new ArrayList<>();
        for (CertificatePictureEntity one:certificatePictureEntities){
            Integer type = one.getPictureType();
            String picture = one.getPicture();
            if (type == 0)  mentouPictures.add(picture);
            else if (type == 1) chengliePictures.add(picture);
            else if (type == 2) hetongPictures.add(picture);
        }
        customerDetailVo.setMentouPictures(mentouPictures);
        customerDetailVo.setChengliePictures(chengliePictures);
        customerDetailVo.setHetongPictures(hetongPictures);

        return ResponseData.success(customerDetailVo);
    }

    @PostMapping("/updateUserStatus")
    @ApiOperation("后台根据用户id修改用户的审核状态")
    @ApiImplicitParams ({
        @ApiImplicitParam(name = "uid", value = "用户id", paramType = "query", dataType = "Long", required = true),
        @ApiImplicitParam(name = "status", value = "更改用户的状态", paramType = "query", dataType = "Integer", required = true)
    })
    public ResponseData updateUserStatus(@RequestParam("uid")Long uid,@RequestParam("status")Integer status) {
        UserEntity userEntity = new UserEntity();
        userEntity.setVerifyStatus(status);
        userEntity.setUid(uid);
        userService.updateInfo(userEntity);

        return ResponseData.success("修改成功");
    }

    @PostMapping("/getAllUserByPermission")
    @ApiOperation("后台根据用户权限获取所有用户")
    public ResponseData<Page<UserEntity> > getAllUserByPermission(@RequestParam(required = true) Map<String,Object> params) {
        int verifyStatus = Integer.parseInt((String) params.get("verifyStatus"));
        Page<UserEntity> page = userService.getAllUserByPermission(params, verifyStatus);
        return ResponseData.success(page);
    }


    @PostMapping("/getOrderByOrderStatus")
    @ApiOperation("根据订单状态码获取所有订单信息")
    @ApiImplicitParam(name = "orderStatus", value = "订单状态,0：待付款1：待发货2：待收货3：已收货", paramType = "query", dataType = "Integer", required = false,allowableValues = "0,1,2,3")
    public ResponseData<List<OrderVo>> getOrderByOrderStatus(@RequestParam(value = "orderStatus",required = false)Integer orderStatus, HttpSession session) {
        ResponseData<List<OrderVo>> orders = orderFeignService.getOrderByUid(orderStatus, new HttpSession() {
            @Override
            public long getCreationTime() {
                return 0;
            }

            @Override
            public String getId() {
                return null;
            }

            @Override
            public long getLastAccessedTime() {
                return 0;
            }

            @Override
            public ServletContext getServletContext() {
                return null;
            }

            @Override
            public void setMaxInactiveInterval(int interval) {

            }

            @Override
            public int getMaxInactiveInterval() {
                return 0;
            }

            @Override
            public HttpSessionContext getSessionContext() {
                return null;
            }

            @Override
            public Object getAttribute(String name) {
                return null;
            }

            @Override
            public Object getValue(String name) {
                return null;
            }

            @Override
            public Enumeration<String> getAttributeNames() {
                return null;
            }

            @Override
            public String[] getValueNames() {
                return new String[0];
            }

            @Override
            public void setAttribute(String name, Object value) {

            }

            @Override
            public void putValue(String name, Object value) {

            }

            @Override
            public void removeAttribute(String name) {

            }

            @Override
            public void removeValue(String name) {

            }

            @Override
            public void invalidate() {

            }

            @Override
            public boolean isNew() {
                return false;
            }
        });
        return orders;
    }

    @GetMapping("/updateInfo")
    @ApiOperation("更新用户头像和昵称")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "avatar", value = "头像地址", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "nickname", value = "昵称", paramType = "query", dataType = "String", required = true)
    })
    public ResponseData updateInfo(@RequestParam("avatar")String avatar, @RequestParam("nickname")String nickname, HttpSession session) {
        UserEntity user = (UserEntity) session.getAttribute("loginuser");
        Long uid = user.getUid();

        //更新用户的昵称和头像
        UserEntity updateUserInfo = new UserEntity();
        updateUserInfo.setAvatar(avatar);
        updateUserInfo.setNickname(nickname);
        updateUserInfo.setUid(uid);
        int flag = userService.updateInfo(updateUserInfo);
        if (flag != 1){
            return ResponseData.success("用户信息更新失败",false);
        }
        user.setNickname(nickname);
        user.setAvatar(avatar);
        session.setAttribute("loginuser",user);
        return ResponseData.success("用户信息更新成功",true);
    }

    @ApiOperation("根据用户类别获取所有员工信息")
    @GetMapping("/getAllPeopleByPermission/{permission}")
    @ApiImplicitParam(name = "permission",value = "用户类别",paramType = "path",dataType = "int",required = true)
    public ResponseData<List<UserEntity>> getAllPeopleByPermission(@PathVariable("permission") Long permission){
        List<UserEntity> users = userService.getAllPeople(permission);
        return ResponseData.success(users);
    }

//    /**
//     * 信息
//     */
    @ApiOperation("根据用户id查询用户信息")
    @GetMapping("/info/{uid}")
    public R getKehuInfo(@ApiParam("用户id") @PathVariable("uid") Long uid){
		UserEntity user = userService.getById(uid);

        return R.ok().put("user", user);
    }
//
//    /**
//     * 保存
//     */
//    @RequestMapping("/save")
//    public R save(@RequestBody UserEntity user){
//		userService.save(user);
//
//        return R.ok();
//    }
//
//    /**
//     * 修改
//     */
//    @RequestMapping("/update")
//    public R update(@RequestBody UserEntity user){
//		userService.updateById(user);
//
//        return R.ok();
//    }
//
//    /**
//     * 删除
//     */
//    @RequestMapping("/delete")
//    public R delete(@RequestBody Long[] uids){
//		userService.removeByIds(Arrays.asList(uids));
//
//        return R.ok();
//    }

    @ApiOperation("获取所有员工，不包括客户")
    @GetMapping("/getAllUser")
    public ResponseData<List<UserEntity>> getAllUser(){
        List<UserEntity> userList = userService.list(new QueryWrapper<UserEntity>().eq("permission", 1));
        return ResponseData.success(userList);
    }

    @ApiOperation("通过用户名或手机号获取用户")
    @GetMapping("/getUserByMobileOrNickname")
    public UserEntity getUserByMobileOrNickname(@ApiParam("手机号") @RequestParam(value = "mobile",required = false) String mobile,
                                                @ApiParam("用户名") @RequestParam(value = "nickname",required = false) String nickname){
        QueryWrapper<UserEntity> userEntityQueryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(mobile)){
            userEntityQueryWrapper.eq("mobile",mobile);
        }
        if(!StringUtils.isEmpty(nickname)){
            userEntityQueryWrapper.eq("nickname",nickname);
        }
        return userService.getOne(userEntityQueryWrapper,false);
    }

}
